document.addEventListener("DOMContentLoaded", function() {
    fetchUserInfo();
});

let currentUserId;
let currentUsername;
let currentAvatarUrl;

function fetchUserInfo() {
    fetch('http://101.34.242.206:9990/users/queryCurrentUserInfo')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                currentUserId = data.data.id;
                currentUsername = data.data.nickname;
                currentAvatarUrl = data.data.headerurl;

                document.getElementById('user-nickname').textContent = currentUsername;
                document.getElementById('user-avatar').src = currentAvatarUrl;

                initWebSocket(currentUserId, currentUsername, currentAvatarUrl);
                loadGroupMessages();  // 加载群聊历史记录
            } else {
                alert('您还未登录！');
            }
        })
        .catch(error => {
            console.error('Error fetching user data:', error);
            alert('您还未登录！');
        });
}

function initWebSocket(userId, username, avatarUrl) {
    const messageInput = document.getElementById('message-input');
    const chatBox = document.getElementById('chat-box');

    const ws = new WebSocket(`ws://101.34.242.206:9990/websocket/${userId}`);

    ws.onopen = function() {
        console.log('WebSocket连接已打开');
    };

    ws.onmessage = function(event) {
        try {
            const message = JSON.parse(event.data);
            console.log("接收到的消息：", message);  // 调试信息
            displayMessage(message, chatBox);
        } catch (e) {
            console.error("解析消息时出错：", e, event.data);
        }
    };

    ws.onclose = function() {
        console.log('WebSocket连接已关闭');
    };

    ws.onerror = function(error) {
        console.log('WebSocket发生错误: ' + error.message);
    };

    window.sendMessage = function() {
        const messageText = messageInput.value.trim();

        if (messageText !== "") {
            const message = {
                content: messageText,
                messageType: 'group',
                headerUrl: avatarUrl,
                name: username
            };

            const messageString = JSON.stringify(message);
            console.log("发送的消息：", messageString);
            ws.send(messageString);

            // Don't display message here to avoid duplicate
            // displayMessage(message, chatBox);

            messageInput.value = "";
        }
    };

    messageInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            sendMessage();
        }
    });
}

function displayMessage(message, chatBox) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message');

    // 处理消息内容，将带引号的整个消息转换为超链接
    const messageText = message.content || message.message;
    const quoteRegex = /"([^"]*?\((https?:\/\/[^\s()]+)\))"/;
    let messageContent = messageText;

    const urlMatch = messageText.match(quoteRegex);
    if (urlMatch) {
        const fullText = urlMatch[1]; // 引号内的完整文本
        const url = urlMatch[2]; // 括号内的 URL
        const linkedMessage = `<a href="${url}" target="_blank">${fullText}</a>`;
        messageContent = messageText.replace(quoteRegex, linkedMessage);
    }

    messageElement.innerHTML = `
        <img src="${message.headerUrl}" alt="头像" class="avatar">
        <div class="message ${message.name === currentUsername ? 'user' : 'bot'}">
            <span class="message-name">${message.name}</span>
            <span>${messageContent}</span>
        </div>
    `;

    chatBox.appendChild(messageElement);
    chatBox.scrollTop = chatBox.scrollHeight;
}






function loadGroupMessages() {
    fetch('http://101.34.242.206:9990/webSocket/getGroupMessage')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                const messages = data.data;
                const chatBox = document.getElementById('chat-box');
                messages.forEach(message => {
                    displayMessage({
                        message: message.message,
                        messageType: message.messageType,
                        headerUrl: message.headerUrl,
                        name: message.name
                    }, chatBox);
                });
            } else {
                console.error('Error loading group messages:', data.message);
            }
        })
        .catch(error => {
            console.error('Error loading group messages:', error);
        });
}


